<template>
 <div>
    <fou-dialog :title="'調堂'" v-model:dialogValue="ticdialog" :width="'75%'" ref="dialog">
        <template #content>
   <table border="1" width='100%' align="center" cellpadding="5" cellspacing="5">
		<caption >原本課程</caption>
		<tr border="1">
			<th>課程名稱</th>
			<th>課程編號</th>
			<th>上課時間</th>
			<th>導師</th>
			<th>上課人數</th>
	    </tr>
		<tr border="1">
			<td align="center">{{originCourse.name}}</td>
			<td align="center">{{originCourse.course && originCourse.course.number}}</td>
			<td align="center">{{originCourse.courseTime}}</td>
			<td align="center">{{originCourse.teacher}}</td>
			<td align="center">{{originCourse.count}}</td>
	    </tr>
	</table>

        <el-form    ref="ruleFormRef" class="mt-[15px]" >
             <el-row :gutter="24">
                  <el-col :span="8">
                    <el-form-item  label="课程 報讀課程：" >
                        <el-button  @click="switchCourses('course','coursecate','courseList')" >{{initialCourse.name}}</el-button>
                    </el-form-item>
                  </el-col>
                <el-col :span="8">
                  <!-- <el-form-item label="日期" prop="rules_date"> -->
                        <!-- <date-controls :isFlash="false" ref="datecontrols" :searchConfig="setFormConfig" @update="update" /> -->
                        <el-button class="ml-[15px]"  @click="addcourse" type="primary" circle icon="Search"></el-button>
                        
                  <!-- </el-form-item> -->
                </el-col>
                <el-col :span="8">
                  <el-button @click="register" style="color:#fff" color="#50BC58">登記</el-button>
                </el-col>
                <el-col :span="24">
                <ProTable
                ref="accountRef"
                :data="list"
                :page="{}"
                :column="columned"
                :rowControl="[]"
                :elProps="{border:true,selection:true,height:300,headerCellClassName:cellClass}"
                :disabled="[]"
                :controlWidth="{}"
                @selection-change="onSelectionChange"
                @select-click="selectClick"
                >
                <template #default="{ row, propname }">
                    <div v-if="propname === 'teacher'">{{row[propname]?.ename}}</div>
                </template>
                </ProTable>
                </el-col>
             </el-row>

                                           <ProTable
                :data="courseList"
                :page="{}"
                :column="columned"
                :rowControl="[]"
                :elProps="{border:true,selection:false,height:300}"
                :disabled="[]"
                :controlWidth="{}"
                @selection-change="onSelectionChange"
                >
                <template #default="{ row, propname }">
                    <div v-if="propname === 'teacher'">{{row[propname]?.ename}}</div>
                </template>
                <template #search_operate>
                    <el-table-column  fixed="right" min-width="50px" >
                        <template #default="scope">
                            <el-link class="flex justify-center" type="primary" :underline="false" @click="handleDelete(scope.row,scope.$index, )" >删除</el-link >
                        </template>
                    </el-table-column>
                </template>
                </ProTable>
           </el-form>
        </template>
        <template #footer>
            <div class="flex justify-end ">
                <el-button @click="ticdialog = false">取消</el-button>
                <el-button color="#081F42" @click="confirm">確定</el-button>
            </div>
        </template>
    </fou-dialog>
    <CheckCourse ref="CourseProductsRef" @update="getCourseProducts"></CheckCourse>
 </div>
</template>

<script setup>
import {ref,reactive} from 'vue'
import { dayjs } from "element-plus";
import {studentHall,course} from '@/http/index.js'
import {message, loading ,closeLoading} from '@/common/function.js'
import {setFormConfig} from './index.js'
import isoWeekday from 'dayjs/plugin/isoWeek'
import isBetween from 'dayjs/plugin/isBetween'
import CheckCourse from './checkCourse.vue'
dayjs.extend(isoWeekday)
dayjs.extend(isBetween)
const cellClass = (row) => {
    if (row.columnIndex === 0) {
      return "DisableSelection";
    } 
    return "";
  };
const columned = {
  name:'課程名稱',
  number:'課程編號',
  date:'日期',
  time1:'時間',
  teacher:'導師',
  nums:'上課人數'
}
// const form = reactive({
//     student_id:localStorage.getItem('student_id'),
// });
const ticdialog = ref(false)
const originCourse = ref({})
const datecontrols = ref([])
const student_id = ref('')
const initialCourse = ref({})
const init = (e,id)=>{
  console.log(e);
    student_id.value = id
    originCourse.value = e
    ticdialog.value = true
    // datecontrols.value.value = []
    list.value = []
    courseList.value = []
    selectList.value = []
    courseSelect(e)
}
const courseSelect = async (e)=>{
    let obj = reactive({
  school_id:localStorage.getItem('school_id'),
  page:1,
  limit: 100,
  name: e.name,
  status:1,
});
    loading()
    const data = await course(obj)
    if (data.code == 200) {
        initialCourse.value = data.data.data[0]
    }
    closeLoading()
}
const list = ref([])
const addcourse = ()=>{
  // if (!time.value  ||time.value.length < 1) {
  //   return message('請選擇日期','warning')
  // }
    let equation = initialCourse.value
    console.log(equation);
  // if (dayjs(time.value[0]).isBetween(equation.start_time, dayjs(equation.end_time),null, '[[')
  // && dayjs(time.value[1]).isBetween(equation.start_time, dayjs(equation.end_time),null, '[[')) {
      let dateStart = dayjs(dayjs(`${new Date()}`)),
  dateEnd = dayjs(equation.end_time),
  dateDiff = dateEnd.diff(dateStart, 'days'),
  weekVal =equation.week.split(',').map(Number),
  newList = [],
  j = 0,
  chineseWeek = ['一', '二', '三', '四', '五', '六', '日'];
  console.log(dateStart.format('YYYY-MM-DD hh:mm:ss'),dateEnd.format('YYYY-MM-DD hh:mm:ss'),dateDiff);
  let rules_time =  equation.time.split('-')[0]
        while (dateDiff >= j) {
            let num = dayjs(dayjs(`${new Date()}`)).add(j, 'days').isoWeekday()
          weekVal.forEach((v, i) => {
            if (v === num) {
              let obj = dayjs(dayjs(`${new Date()}`).format('YYYY-MM-DD')).add(j, 'days')
              let strs = rules_time.split(':')
              let completeStartDate = dayjs(obj).add(parseInt(strs[0]), 'hours').add(parseInt(strs[1]), 'minutes')
                .format('YYYY-MM-DD HH:mm')
              let completeEndDate = dayjs(obj).add(parseInt(strs[0]), 'hours').add(parseInt(strs[1]) + parseInt(
                60), 'minutes').format('YYYY-MM-DD HH:mm')
              // return
              let formData = {
                ...equation
              }
              formData.time1 = `${completeStartDate.split(' ')[1]}-${completeEndDate.split(' ')[1]}`
              formData.date = `${dayjs(obj).format('YYYY-MM-DD')}(${chineseWeek[v-1]})`
              // formData.NumberPeople = `${formData.number}/${formData.maxNumber}`
              formData.start_time = `${completeStartDate}:00`
              formData.end_time = `${completeEndDate}:00`
              formData.type = '1'
            //   formData.status = formData.auditoriumStatus == '1' ? '試堂' : '未上課'
              formData.status  == '1' ? '欠款' : '未上課'
              delete formData.rules_date
              delete formData.rules_time
              newList.unshift(formData)
            }
          })
          j++
        }
        console.log(newList);
        newList.map(e=>{
          e.nums = e.num
          e.num = 1
        })
        list.value = newList.reverse()
        return newList
  // }else{
  //   message('所選課程不在可使用時間範圍','warning')
  // }
}

//选择课程
const CourseProductsRef = ref('')
const switchCourses = async(url,type_url,indexUrl)=>{
  console.log(url,type_url,indexUrl);
    CourseProductsRef.value.indexUrl = indexUrl //點擊哪一分類
    CourseProductsRef.value.TableDatatype(type_url)//類別
    await CourseProductsRef.value.TableData(url)//列表
    CourseProductsRef.value.CourseProductsDia = true
}
const getCourseProducts = (row,type,indexUrl)=>{
  console.log(row,type,indexUrl);
  console.log(originCourse.value);
initialCourse.value = row[0]
}

const accountRef = ref('')
const dialog = ref('')
// 多选
const selectList = ref([])
const onSelectionChange = (list, row)=>{
}
const selectClick = (selection, row)=>{
       if (selection.length === 0) {
        return
      }
      accountRef.value.multipleTableRef.clearSelection()
      list.value.forEach((ele) => {
        if (ele.date === row.date) {
          accountRef.value.multipleTableRef.toggleRowSelection(ele, true)
          selectList.value = [ele]
        }
      })
}
const courseList = ref([])
// 登记调堂
const register = ()=>{
courseList.value = selectList.value
}
// 删除登记
const handleDelete = (row,index)=>{
  courseList.value.splice(index,1)
}
const time = ref([])
const update = (e)=>{
time.value = e
}
const emit = defineEmits(['update'])
const confirm = async ()=>{
  let form = {
    school_id:localStorage.getItem('school_id'),
    student:[]
  }
  form.student = courseList.value.map(e=>({
    course_id:e.id,
    start_time:e.start_time,
    end_time:e.end_time,
    classStudentid:originCourse.value?.classStudentid,
    admin_id:originCourse.value?.admin_id,
    classroom_id:e.classroom_id,
    student_id:student_id.value,
    
  }))
  const data = await studentHall(form)
  if (data.code == 200) {
    ticdialog.value = false
    emit('update')
    message('成功修改上課時間')
  }else{
    message(data.response.data.message,'warning')
  }
}
defineExpose({
    init
})
</script>

<style scoped lang='less'>
table{
border-collapse: collapse;
caption{
	border:1px solid #ebeef5;
    padding: 5px 0 !important;
}
tr{
	border:1px solid #ebeef5;
     td{
    border: 1px solid #ebeef5;
    }
    th{
    border: 1px solid #ebeef5;
    }
}
}


::v-deep .el-table .DisableSelection .cell .el-checkbox__inner{
  display: none;
}
</style>